package com.sec.datasource.datasource.aop;

import com.sec.datasource.datasource.config.DataSourceContextHolder;
import com.sec.datasource.datasource.config.enums.DataSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Order(-1)
@Component
public class DataSourceAspect {

    @Pointcut("execution(* com.sec.datasource.datasource.mapper.onedb.*.*(..))")
    private void onedbAspect() {
    }

    @Pointcut("execution(* com.sec.datasource.datasource.mapper.twodb.*.*(..))")
    private void twodbAspect() {
    }

    @Before("onedbAspect()")
    public void onedb() {
        log.info("select to datasource one");
        DataSourceContextHolder.setDataSource(DataSourceEnum.ONE_DB);
    }

    @Before("twodbAspect()")
    public void twodb() {
        log.info("select to datasource two");
        DataSourceContextHolder.setDataSource(DataSourceEnum.TWO_DB);
    }

    @After("onedbAspect() || twodbAspect()")
    public void doAfter(){
        DataSourceContextHolder.clear();
    }

}
